package com.um.jdy.mp.report.service.impl;

import cn.hutool.core.date.DateUtil;
import com.um.jdy.common.charge.dao.OrderDao;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.member.enums.MemberEnum;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.mp.commission.manager.CommissionManager;
import com.um.jdy.mp.report.entity.vo.OrderDataItemVO;
import com.um.jdy.mp.report.entity.vo.OrderItemVO;
import com.um.jdy.mp.report.entity.vo.OrderSummaryVO;
import com.um.jdy.mp.report.entity.vo.StationOrderItemVO;
import com.um.jdy.mp.report.enums.DateType;
import com.um.jdy.mp.report.service.OrderDataService;
import com.um.jdy.mp.user.service.SessionUserService;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 运营商订单统计
 *
 * @author 邓南辉
 * 日期 2023/2/28
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Slf4j
public class OrderDataServiceImpl extends BaseEntityServiceImpl<OrderDao, Order> implements OrderDataService {
    
    @Autowired
    OrderDao orderDao;
    
    @Autowired
    MerchantService merchantService;
    
    @Autowired
    SessionUserService sessionUserService;

    @Autowired
    CommissionManager commissionManager;

    private String getAccountType(){
        return sessionUserService.getTokenUser().getType();
//        return "merchant";
    }

    private Integer allDaySeconds(DateType data_type) {
        Integer days = 1;
        if (data_type == DateType.Week) {
            days = 7;
        } else if (data_type == DateType.Month) {
            days = 30;
        } else if (data_type == DateType.ThreeMonth) {
            days = 90;
        } else if (data_type == DateType.HalfOfYears) {
            days = 180;
        } else if (data_type == DateType.Years) {
            days = 365;
        }
        return days * 24 * 3600;
    }

    private String getStartDate(DateType data_type) {
        Date now = new Date();
        if (data_type == DateType.Week) {
            now.setDate(now.getDate() - 6);
        } else if (data_type == DateType.Month) {
            now.setDate(now.getDate() - 29);
        } else if (data_type == DateType.ThreeMonth) {
            now.setDate(now.getDate() - 89);
        } else if (data_type == DateType.HalfOfYears) {
            now.setDate(now.getDate() - 179);
        } else if (data_type == DateType.Years) {
            now.setDate(now.getDate() - 364);
        }
        return DateUtil.format(now, "yyyy-MM-dd") + " 00:00:00";
    }

    private String getEndDate() {
        return DateUtil.format(new Date(), "yyyy-MM-dd") + " 23:59:59";
    }

    /**
     * 查询累计数据
     *
     * @return
     */
    public OrderSummaryVO getOrderSummary() {
        String endDate = getEndDate();
        OrderSummaryVO orderSummaryVO;
        String sqlName = "get_agent_or_sharing_order_summary";
        if(getAccountType().equals(MemberEnum.UserType.merchant.name())) {
            sqlName = "get_partners_order_summary";
        }
        orderSummaryVO = orderDao.getViewModel(sqlName, OrderSummaryVO.class, new Object[]{getAccountType(),endDate,sessionUserService.getTokenUserId()});
        orderSummaryVO.setEndDate(new Date());

        return orderSummaryVO;
    }

    /**
     * 查询订单统计
     *
     * @return
     */
    public List<OrderDataItemVO> getOrderData( DateType data_type, String stationId) {
        String startDate = getStartDate(data_type);
        String endDate = getEndDate();
        List<OrderDataItemVO> list;

        list = orderDao.getViewModelList("get_partners_order_list", OrderDataItemVO.class, new Object[]{getAccountType(), startDate, endDate, sessionUserService.getTokenUserId(), StringUtil.getTrim(stationId, "%")});


        List<OrderDataItemVO> returnList = new ArrayList<>();
        Date beginDays = DateUtil.parseDate(startDate.substring(0, 10));
        Date endDays = DateUtil.parseDate(endDate.substring(0, 10));
        while (beginDays.getTime() <= endDays.getTime()) {
            String date = DateUtil.format(beginDays, "yyyy-MM-dd");
            log.info("dete:{}", date);
            boolean exist = false;
            for (int index = 0; index < list.size(); index++) {
                OrderDataItemVO orderDataItemVO = list.get(index);
                if (date.equals(DateUtil.format(orderDataItemVO.getCreateDate(), "yyyy-MM-dd"))) {
                    exist = true;
                    returnList.add(orderDataItemVO);
                    break;
                }
            }
            if (!exist) {
                OrderDataItemVO item = new OrderDataItemVO();
                item.setCreateDate(DateUtil.parseDate(date));
                item.setNum(0);
                item.setReturnAmount(0);
                item.setTotalAmount(0);
                item.setTotalProfit(0);
                returnList.add(item);
            }

            beginDays.setDate(beginDays.getDate() + 1);
        }

        return returnList;

    }

    /**
     * 分页查询设备订单
     *
     * @param pageNo
     * @param pageSize
     * @param data_type
     * @param stationId
     * @return
     */
    public Page<OrderItemVO> getDeviceOrderPage(int pageNo, int pageSize, DateType data_type,  String stationId) {
        Page<OrderItemVO> page = new Page(pageSize);
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        String startDate = getStartDate(data_type);
        String endDate = getEndDate();
        String sqlName = "get_partners_device_order_page";
        String sqlCountName = "get_partners_device_order_count";

        PageParams params = new PageParams();

        if(sessionUserService.getTokenUser().getType().equals("merchant")) {
            params.getCondition().put("p.platform_merchant_id", sessionUserService.getTokenUser().getPlatformMerchantId());
        }
        return getCMSViewModelPageBySqlName(page, sqlName, sqlCountName, OrderItemVO.class, params.getProperties(), params.getValues(),
                new ArrayList<>(), new String[]{}, new String[]{}, new Object[]{startDate, endDate, sessionUserService.getTokenUserId(), StringUtil.getTrim(stationId, "%")}, false);

    }

    /**
     * 分页查询站场订单
     *
     * @param pageNo
     * @param pageSize
     * @param data_type
     * @return
     */
    public Page<StationOrderItemVO> getStationOrderPage(int pageNo, int pageSize, DateType data_type) {
        Page<StationOrderItemVO> page = new Page();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        String startDate = getStartDate(data_type);
        String endDate = getEndDate();
        String sqlName = "get_partners_station_order_page";
        String sqlCountName = "get_partners_station_order_count";
        return getCMSViewModelPageBySqlName(page, sqlName, sqlCountName, StationOrderItemVO.class, new String[]{"s." + sessionUserService.getUserIdName()}, new Object[]{sessionUserService.getTokenUser().getPlatformMerchantId()},
                new ArrayList<>(), new String[]{}, new String[]{}, new Object[]{startDate, endDate, sessionUserService.getTokenUserId()}, false);

    }
}
